package com.san.system.controller;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.san.base.controller.BaseController;
import com.san.base.domain.Tree;
import com.san.base.service.DictService;
import com.san.common.annotation.Log;
import com.san.common.utils.AESUtils;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.R;
import com.san.common.utils.ShiroUtils;
import com.san.common.utils.StringUtils;
import com.san.system.domain.DeptDO;
import com.san.system.domain.RoleDO;
import com.san.system.domain.UserDO;
import com.san.system.service.RoleService;
import com.san.system.service.UserService;
import com.san.system.vo.UserVO;

@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	private final static String KEY = "idcard";
	private String prefix = "system/user";
	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	DictService dictService;

	@RequiresPermissions("sys:user:view")
	@GetMapping("")
	String user(Model model) {
		return prefix + "/view";
	}

	@GetMapping("/list")
	@ResponseBody
	PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<UserDO> sysUserList = userService.list(query);
		int total = userService.count(query);
		PageUtils pageUtil = new PageUtils(sysUserList, total);
		return pageUtil;
	}

	@RequiresPermissions("sys:user:add")
	@Log("添加用户")
	@GetMapping("/add")
	String add(Model model) {
		List<RoleDO> roles = roleService.list();
		model.addAttribute("roles", roles);
		return prefix + "/add";
	}

	@RequiresPermissions("sys:user:edit")
	@Log("编辑用户")
	@GetMapping("/edit/{id}")
	String edit(Model model, @PathVariable("id") Long id) {
		try {
			UserDO userDO = (UserDO)userService.getById(id);
			if (userDO.getIdentityId() != null) {
				String sfIdNoRncrypt = AESUtils.AESDecode(KEY, userDO.getIdentityId());
				String newIdentityId = StringUtils.idMask(sfIdNoRncrypt, 3, 3);
				userDO.setShowIdentityId(newIdentityId);
				userDO.setIdentityId(sfIdNoRncrypt);
			}
			model.addAttribute("user", userDO);
			List<RoleDO> roles = roleService.list(id);
			model.addAttribute("roles", roles);
		} catch (Exception e) {
			logger.error("获取用户信息失败",e);
		}
		
		return prefix + "/edit";
	}

	@RequiresPermissions("sys:user:add")
	@Log("保存用户")
	@PostMapping("/save")
	@ResponseBody
	R save(UserDO user) {
		user.setUserIdCreate(getUserId());
		user.setIdentityId(AESUtils.AESEncode(KEY, user.getIdentityId()));
		try {
			if (userService.save(user) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("保存用户信息失败",e);
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:edit")
	@Log("更新用户")
	@PostMapping("/doEdit")
	@ResponseBody
	R doEdit(UserDO user) {
		if (user.getIdentityId() != null) {
			user.setIdentityId(AESUtils.AESEncode(KEY, user.getIdentityId()));
		}
		try {
			if (userService.doEdit(user) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("更新用户信息失败",e);
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:edit")
	@Log("更新用户")
	@PostMapping("/updatePeronal")
	@ResponseBody
	R updatePeronal(UserDO user) {
		if (userService.updatePersonal(user) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:remove")
	@Log("删除用户")
	@PostMapping("/remove")
	@ResponseBody
	R remove(Long id) {
		try {
			if (userService.remove(id) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("删除用户失败",e);
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:batchRemove")
	@Log("批量删除用户")
	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] ids) {
		try {
			int r = userService.batchRemove(ids);
			if (r > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("批量删除用户失败",e);
		}
		
		return R.error();
	}

	@PostMapping("/exit")
	@ResponseBody
	boolean exit(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return !userService.exit(params);
	}

	@RequiresPermissions("sys:user:resetPwd")
	@Log("请求更改用户密码")
	@GetMapping("/resetPwd/{id}")
	String resetPwd(@PathVariable("id") Long userId, Model model) {

		UserDO userDO = new UserDO();
		userDO.setUserId(userId);
		model.addAttribute("user", userDO);
		return prefix + "/reset_pwd";
	}

	@Log("提交更改用户密码")
	@PostMapping("/resetPwd")
	@ResponseBody
	R resetPwd(UserVO userVO) {
		try {
			userService.resetPwd(userVO, getUser());
			ShiroUtils.logout();
			return R.ok();
		} catch (Exception e) {
			return R.error(1, e.getMessage());
		}

	}

	@RequiresPermissions("sys:user:resetPwd")
	@Log("admin提交更改用户密码")
	@PostMapping("/adminResetPwd")
	@ResponseBody
	R adminResetPwd(UserVO userVO) {
		try {
			userService.adminResetPwd(userVO);
			return R.ok();
		} catch (Exception e) {
			return R.error(1, e.getMessage());
		}

	}

	@GetMapping("/tree")
	@ResponseBody
	public Tree<DeptDO> tree() {
		Tree<DeptDO> tree = new Tree<DeptDO>();
		tree = userService.getTree();
		return tree;
	}

	@GetMapping("/treeView")
	String treeView() {
		return prefix + "/userTree";
	}

	@GetMapping("/personal")
	String personal(Model model) {
		try {
			UserDO userDO = (UserDO)userService.getById(getUserId());
			model.addAttribute("user", userDO);
		} catch (Exception e) {
			logger.error("获取用户信息失败",e);
		}
		
		return prefix + "/personal";
	}
}
